import taskService from "@/api/services/taskService";
import type { TaskSubmitRecord } from "@/api/services/taskService";
import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import { Modal } from "antd";
import { taskSubmitStatusMap } from "@/constants/status";
import {
	Button,
	Card,
	Descriptions,
	Image,
	Space,
	Table,
	Tag,
	Tooltip,
	Typography,
	Drawer,
	message,
	Input,
	Form,
	Select,
	Row,
	Col,
	DatePicker,
	Popconfirm,
	InputNumber,
} from "antd";
import { ConfigProvider } from "antd";
import zhCN from "antd/lib/locale/zh_CN";
// import "moment/dist/locale/zh-cn";
const ZhCNLocale: typeof zhCN = zhCN;
ZhCNLocale.DatePicker!.lang = {
	...zhCN.DatePicker!.lang,
	monthFormat: "M月",
	shortWeekDays: ["日", "一", "二", "三", "四", "五", "六"],
};

import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import dayjs from "dayjs";
import { useParams } from "react-router-dom";
import { renderFieldValue } from "@/utils/renderField";
import UserDetailModal from "./user-detail-modal";

export default function TaskSubmitListPage() {
	const { id = "" } = useParams();
	const [urlSearchParams] = useSearchParams();
	const taskId = urlSearchParams.get("taskId");

	const [loading, setLoading] = useState(false);
	const [records, setRecords] = useState<TaskSubmitRecord[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [reviewModalVisible, setReviewModalVisible] = useState(false);
	const [reviewingRecord, setReviewingRecord] = useState<TaskSubmitRecord>();
	const [reviewRemark, setReviewRemark] = useState("");
	const [reviewLoading, setReviewLoading] = useState(false);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [searchForm] = Form.useForm();
	const [searchParams, setSearchParams] = useState({
		status: undefined,
		keyword: "",
		category_id: undefined,
		task_id: undefined,
		start_time: undefined,
		end_time: undefined,
	});
	const [categories, setCategories] = useState<
		{ label: string; value: number }[]
	>([]);
	const [tasks, setTasks] = useState<{ label: string; value: number }[]>([]);
	const [userDetailOpen, setUserDetailOpen] = useState(false);
	const [currentRecord, setCurrentRecord] = useState<TaskSubmitRecord | null>(
		null,
	);

	// 获取任务分类列表
	const fetchCategories = async () => {
		try {
			const res = await taskService.categoryList({ page: 1, limit: 100 });
			const options = res.items.map((item) => ({
				label: item.name,
				value: item.id,
			}));
			setCategories(options);
		} catch (error) {
			console.error("获取任务分类失败:", error);
		}
	};

	// 获取任务列表
	const fetchTasks = async (categoryId?: number) => {
		try {
			const params: any = { page: 1, limit: 100 };
			if (categoryId) {
				params.category_id = categoryId;
			}
			const res = await taskService.taskList(params);
			const options = res.items.map((item) => ({
				label: item.title,
				value: item.id,
			}));
			setTasks(options);
		} catch (error) {
			console.error("获取任务列表失败:", error);
		}
	};

	useEffect(() => {
		fetchCategories();
		fetchTasks()
	}, []);

	// 当分类改变时，重新获取任务列表
	const handleCategoryChange = (value: number | undefined) => {
		searchForm.setFieldValue("task_id", undefined);
		setTasks([]);
		// 无论是选择具体分类还是全部分类，都重新获取任务列表
		fetchTasks(value);
	};

	const fetchRecords = async (page = 1, limit = 10) => {
		setLoading(true);
		try {
			const res = await taskService.taskSubmitList({
				page,
				limit,
				task_id:
					searchParams.task_id || (taskId ? parseInt(taskId) : undefined),
				category_id: searchParams.category_id,
				status: searchParams.status,
				keyword: searchParams.keyword,
				start_time: searchParams.start_time,
				review_start_time: searchParams.review_start_time,
				review_end_time: searchParams.review_end_time,
				end_time: searchParams.end_time,
			});
			setRecords(res.items);
			setTotal(res.total);
		} catch (error) {
			message.error("获取提交记录列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchRecords(currentPage, pageSize);
	}, [currentPage, pageSize, taskId, searchParams]);

	const getSearchParams = async () => {
		const values = await searchForm.validateFields();
		const { timeRange, reviewtimeRange, ...restValues } = values;
		console.log(restValues, reviewtimeRange);
		return {
			...restValues,
			task_id: taskId ? Number(taskId) : restValues.task_id,
			start_time: timeRange
				? Math.floor(timeRange[0].startOf("day").valueOf() / 1000)
				: undefined,
			end_time: timeRange
				? Math.floor(timeRange[1].endOf("day").valueOf() / 1000)
				: undefined,
			review_start_time: reviewtimeRange
				? Math.floor(reviewtimeRange[0].startOf("day").valueOf() / 1000)
				: undefined,
			review_end_time: reviewtimeRange
				? Math.floor(reviewtimeRange[1].endOf("day").valueOf() / 1000)
				: undefined,
		};
	};

	const handleSearch = async () => {
		const params = await getSearchParams();
		setSearchParams(params);
		setCurrentPage(1);
	};

	const handleReset = () => {
		searchForm.resetFields();
		setSearchParams({
			status: undefined,
			keyword: "",
			category_id: undefined,
			task_id: undefined,
			start_time: undefined,
			end_time: undefined,
			review_start_time: undefined,
			review_end_time: undefined,
		});
		setCurrentPage(1);
	};

	const handleBatchReview = async (status: number) => {
		if (selectedRowKeys.length === 0) {
			message.warning("请选择要审核的记录");
			return;
		}

		Modal.confirm({
			title: "批量审核",
			content: (
				<div>
					<p>
						确定要{status === 1 ? "通过" : "拒绝"}选中的{" "}
						{selectedRowKeys.length} 条记录吗？
					</p>
					<Input.TextArea
						rows={4}
						placeholder="请输入审核意见"
						defaultValue={reviewRemark}
						onChange={(e) => setReviewRemark(e.target.value)}
						style={{ marginTop: "16px" }}
					/>
				</div>
			),
			onOk: async () => {
				try {
					await Promise.all(
						selectedRowKeys.map((id) =>
							taskService.taskSubmitReview(
								Number(id),
								status,
								reviewRemark,
								undefined,
							),
						),
					);
					message.success("批量审核成功");
					setSelectedRowKeys([]);
					setReviewRemark("");
					// 刷新当前页面数据
					await fetchRecords(currentPage, pageSize);
					// 如果当前有打开的记录详情，刷新它的状态
					// if (reviewingRecord) {
					// 	const updatedRecord = await taskService.taskSubmitDetail(
					// 		reviewingRecord.id,
					// 	);
					// 	setReviewingRecord(updatedRecord);
					// }
				} catch (error) {
					message.error("批量审核失败");
				}
			},
		});
	};

	const handleReview = async (status: number) => {
		if (!reviewingRecord) return;

		setReviewLoading(true);
		try {
			await taskService.taskSubmitReview(
				reviewingRecord.id,
				status === -1 ? -1 : status,
				reviewRemark,
				reviewingRecord.price,
			);
			message.success("审核成功");
			setReviewRemark("");
			// 刷新当前页面数据
			await fetchRecords(currentPage, pageSize);
			// 重新获取当前记录的最新状态
			const updatedRecord = await taskService.taskSubmitInfo(
				reviewingRecord.id,
			);
			setReviewingRecord(updatedRecord);
		} catch (error) {
			message.error("审核失败");
		} finally {
			setReviewLoading(false);
		}
	};

	const handleExport = async () => {
		try {
			const params = await getSearchParams();
			const res = await taskService.taskRecordExport({
				...params,
			});
			window.open(res.url, "_blank");
		} catch (error) {
			console.error("导出失败:", error);
			message.error("导出失败");
		}
	};

	const rowSelection = {
		selectedRowKeys,
		onChange: (newSelectedRowKeys: React.Key[]) => {
			setSelectedRowKeys(newSelectedRowKeys);
		},
		getCheckboxProps: (record: TaskSubmitRecord) => ({
			disabled: record.status !== 0,
		}),
	};

	const columns: ColumnsType<TaskSubmitRecord> = [
		{
			title: "任务信息",
			dataIndex: "task",
			width: 280,
			render: (_, record) => (
				<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
					<div>
						<Typography.Text strong style={{ fontSize: "16px" }}>
							{record.task?.title || "-"}
						</Typography.Text>
						<Typography.Text
							type="secondary"
							style={{ marginLeft: "8px", fontSize: "12px" }}
						>
							#{record.id}
						</Typography.Text>
					</div>
					<div>
						<Tag style={{ borderRadius: "4px" }}>
							{record.task?.category?.name || "-"}
						</Tag>
					</div>
					<div>
						<Typography.Text type="secondary" style={{ fontSize: "14px" }}>
							<Space size={4}>
								提交时间：
								{dayjs(record.createtime * 1000).format("YYYY-MM-DD HH:mm:ss")}
							</Space>
						</Typography.Text>
					</div>

					<div v-if={record.reviewtime > 0}>
						<Typography.Text type="secondary" style={{ fontSize: "14px" }}>
							<Space size={4}>
								审核时间：
								{dayjs(record.reviewtime * 1000).format("YYYY-MM-DD HH:mm:ss")}
							</Space>
						</Typography.Text>
					</div>
					<div>
						<Tag
							color={taskSubmitStatusMap[record.status]?.color}
							style={{ borderRadius: "4px" }}
						>
							{taskSubmitStatusMap[record.status]?.text || "-"}
						</Tag>
					</div>
				</div>
			),
		},

		{
			title: "提交人信息",
			dataIndex: "user",
			width: 200,
			render: (_, record) => (
				<Space
					align="center"
					style={{ cursor: "pointer" }}
					onClick={() => {
						setCurrentRecord(record);
						setUserDetailOpen(true);
					}}
				>
					<div
						style={{
							width: "32px",
							height: "32px",
							borderRadius: "50%",
							background: "#e6f4ff",
							display: "flex",
							alignItems: "center",
							justifyContent: "center",
							color: "#1890ff",
						}}
					>
						<Iconify icon="mdi:user" />
					</div>
					<Space direction="vertical" size={0}>
						<Typography.Text strong>
							{record.user?.nickname || record.user?.username || "-"}
						</Typography.Text>
						<Typography.Text type="secondary" style={{ fontSize: "12px" }}>
							{record.user?.mobile || "-"}
						</Typography.Text>
					</Space>
				</Space>
			),
		},
		{
			title: "提交内容",
			dataIndex: "value",
			render: (values, record) => {
				if (!values?.length) return "-";
				return (
					<div
						style={{
							background: "#fafafa",
							padding: "12px 16px",
							borderRadius: "8px",
							border: "1px solid #f0f0f0",
						}}
					>
						<Space direction="vertical" size={8} style={{ width: "100%" }}>
							{values.map((item, index) => (
								<div
									key={item.id}
									style={{
										display: "flex",
										flexDirection: "column",
										gap: "4px",
									}}
								>
									<Typography.Text type="secondary">
										{item.field?.field_label || `字段${index + 1}`}
									</Typography.Text>
									<div
										style={{
											background: "#fff",
											padding: "8px 12px",
											borderRadius: "4px",
											border: "1px solid #f0f0f0",
											display: "flex",
											alignItems: "center",
											gap: "8px",
										}}
									>
										<Typography.Text style={{ flex: 1 }}>
											{renderFieldValue(item.field?.field_type, item.value)}
										</Typography.Text>
									</div>
								</div>
							))}
							{record.status !== 0 && (
								<div
									style={{
										display: "flex",
										flexDirection: "column",
										gap: "4px",
										marginTop: "8px",
										borderTop: "1px dashed #f0f0f0",
										paddingTop: "8px",
									}}
								>
									<Typography.Text type="secondary">审核意见</Typography.Text>
									<div
										style={{
											background: "#fff",
											padding: "8px 12px",
											borderRadius: "4px",
											border: "1px solid #f0f0f0",
										}}
									>
										<Typography.Text style={{ flex: 1 }}>
											{record.remark || "-"}
										</Typography.Text>
									</div>
								</div>
							)}
						</Space>
					</div>
				);
			},
		},
		{
			title: "操作",
			key: "action",
			width: 80,
			fixed: "right",
			render: (_, record) => (
				<Space>
					{record.status === 0 ? (
						<Tooltip title="审核">
							<IconButton
								onClick={async () => {
									const data = await taskService.taskSubmitInfo(record.id);
									setReviewingRecord(data);
									setReviewModalVisible(true);
								}}
							>
								<Iconify icon="material-symbols:rate-review" />
							</IconButton>
						</Tooltip>
					) : (
						<Tooltip title="查看">
							<IconButton
								onClick={async () => {
									const data = await taskService.taskSubmitInfo(record.id);
									setReviewingRecord(data);
									setReviewModalVisible(true);
								}}
							>
								<Iconify icon="mdi:eye" />
							</IconButton>
						</Tooltip>
					)}
				</Space>
			),
		},
	];

	return (
		<div style={{ padding: "24px", background: "#f5f5f5", minHeight: "100vh" }}>
			<Card bordered={false} style={{ borderRadius: "12px" }}>
				<div
					style={{
						marginBottom: "24px",
						display: "flex",
						alignItems: "center",
						justifyContent: "space-between",
					}}
				>
					<Typography.Title level={4} style={{ margin: 0 }}>
						任务提交记录
					</Typography.Title>
					<Space>
						<Button
							icon={<Iconify icon="mdi:file-export" />}
							onClick={handleExport}
						>
							导出记录
						</Button>
						{selectedRowKeys.length > 0 && (
							<>
								<Button type="primary" onClick={() => handleBatchReview(1)}>
									批量通过
								</Button>
								<Button danger onClick={() => handleBatchReview(-1)}>
									批量拒绝
								</Button>
							</>
						)}
					</Space>
				</div>

				<Form
					form={searchForm}
					layout="inline"
					style={{ marginBottom: "24px" }}
					onFinish={handleSearch}
				>
					<Form.Item name="category_id" label="任务分类">
						<Select
							style={{ width: 160 }}
							options={[{ label: "全部分类", value: "" }, ...categories]}
							placeholder="请选择分类"
							onChange={handleCategoryChange}
							allowClear
						/>
					</Form.Item>
					<Form.Item name="task_id" label="任务">
						<Select
							style={{ width: 200 }}
							options={[{ label: "全部任务", value: "" }, ...tasks]}
							placeholder="请选择任务"
							allowClear
						/>
					</Form.Item>
					<Form.Item name="status" label="状态">
						<Select
							style={{ width: 120 }}
							options={[
								{ label: "全部", value: "" },
								{ label: "未审核", value: 0 },
								{ label: "已通过", value: 1 },
								{ label: "已拒绝", value: -1 },
							]}
							placeholder="请选择状态"
						/>
					</Form.Item>
					<Form.Item name="keyword" label="搜索">
						<Input
							placeholder="请输入关键词"
							style={{ width: 200 }}
							allowClear
						/>
					</Form.Item>
					<Form.Item name="timeRange" label="提交时间">
						<DatePicker.RangePicker
							locale={ZhCNLocale.DatePicker}
							allowClear
							showTime={false}
							style={{ width: 260 }}
						/>
					</Form.Item>
					<Form.Item name="reviewtimeRange" label="反馈时间">
						<DatePicker.RangePicker
							locale={ZhCNLocale.DatePicker}
							allowClear
							showTime={false}
							style={{ width: 260 }}
						/>
					</Form.Item>
					<Form.Item>
						<Space>
							<Button type="primary" htmlType="submit">
								搜索
							</Button>
							<Button onClick={handleReset}>重置</Button>
						</Space>
					</Form.Item>
				</Form>

				<Table
					rowKey="id"
					rowSelection={rowSelection}
					columns={columns}
					dataSource={records}
					loading={loading}
					pagination={{
						current: currentPage,
						pageSize,
						total,
						onChange: (page, size) => {
							setCurrentPage(page);
							setPageSize(size);
						},
						style: { marginTop: "24px" },
					}}
					scroll={{ x: 1000 }}
				/>
			</Card>

			<Drawer
				title={
					<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
						<Iconify
							icon={
								reviewingRecord?.status === 1
									? "material-symbols:check"
									: reviewingRecord?.status === -1
										? "material-symbols:close"
										: "material-symbols:pending"
							}
						/>
						审核任务
					</div>
				}
				open={reviewModalVisible}
				onClose={() => {
					setReviewModalVisible(false);
					setReviewRemark("");
				}}
				width={window.innerWidth > 768 ? 600 : "100%"}
				styles={{
					body: {
						paddingBottom: 80,
					},
				}}
				extra={
					<Space>
						{/* {reviewingRecord?.status === 0 && (
							<>
								<Button
									type="primary"
									danger
									icon={<Iconify icon="material-symbols:close" />}
									onClick={() => handleReview(-1)}
									loading={reviewLoading}
								>
									驳回
								</Button>
								<Button
									type="primary"
									icon={<Iconify icon="material-symbols:check" />}
									onClick={() => handleReview(1)}
									loading={reviewLoading}
								>
									通过
								</Button>
							</>
						)} */}
					</Space>
				}
			>
				<div style={{ padding: "20px 0" }}>
					{reviewingRecord && (
						<div style={{ marginBottom: "24px" }}>
							<div style={{ marginBottom: "16px" }}>
								<Typography.Title level={5} style={{ marginBottom: "8px" }}>
									任务信息 #{reviewingRecord.id}
								</Typography.Title>
								<div
									style={{
										background: "#fafafa",
										padding: "16px",
										borderRadius: "8px",
									}}
								>
									<Space direction="vertical" size={8}>
										<div>
											<Typography.Text type="secondary">
												任务编号：
											</Typography.Text>
											<Typography.Text strong>
												{reviewingRecord.task?.id}
											</Typography.Text>
										</div>
										<div>
											<Typography.Text type="secondary">
												任务名称：
											</Typography.Text>
											<Typography.Text strong>
												{reviewingRecord.task?.title}
											</Typography.Text>
										</div>
										<div>
											<Typography.Text type="secondary">
												提交人：
											</Typography.Text>
											<Typography.Text>
												{reviewingRecord.user?.nickname ||
													reviewingRecord.user?.username ||
													"-"}
											</Typography.Text>
											<Typography.Text
												type="secondary"
												style={{ marginLeft: "16px" }}
											>
												{reviewingRecord.user?.mobile || "-"}
											</Typography.Text>
										</div>
										<div>
											<Typography.Text type="secondary">
												提交时间：
											</Typography.Text>
											<Typography.Text>
												{dayjs(reviewingRecord.createdtime).format(
													"YYYY-MM-DD HH:mm:ss",
												)}
											</Typography.Text>
										</div>
										<div style={{ marginBottom: "8px" }}>
											<Typography.Text type="secondary">
												获得任务价格:{" "}
											</Typography.Text>
											{reviewingRecord.status === 0 ? (
												<InputNumber
													defaultValue={reviewingRecord.price}
													min={0}
													onChange={(value) => {
														if (reviewingRecord) {
															reviewingRecord.price = value;
														}
													}}
													addonAfter="元"
												/>
											) : (
												<Typography.Text>
													{reviewingRecord.price || reviewingRecord.task.price}{" "}
													元
												</Typography.Text>
											)}
										</div>
										<div style={{ marginBottom: "8px" }}>
											<Typography.Text type="secondary">
												当前任务价格:{" "}
											</Typography.Text>
											<Typography.Text>
												{reviewingRecord.task.price} 元
											</Typography.Text>
										</div>
									</Space>
								</div>
							</div>

							<div style={{ marginBottom: "24px" }}>
								<Typography.Title level={5} style={{ marginBottom: "8px" }}>
									提交内容
								</Typography.Title>
								<div
									style={{
										background: "#fafafa",
										padding: "16px",
										borderRadius: "8px",
									}}
								>
									<Space
										direction="vertical"
										size={8}
										style={{ width: "100%" }}
									>
										{reviewingRecord.value?.map((item, index) => (
											<div key={item.id}>
												<Typography.Text type="secondary">
													{item.field?.field_label || `字段${index + 1}`}：
												</Typography.Text>
												<Typography.Text style={{ width: "100%" }}>
													{renderFieldValue(item.field?.field_type, item.value)}
												</Typography.Text>
											</div>
										))}
									</Space>
								</div>
							</div>

							<div>
								<Typography.Title level={5} style={{ marginBottom: "8px" }}>
									{reviewingRecord.status === 0 ? "审核意见" : "审核结果"}
								</Typography.Title>
								{reviewingRecord.status === 0 ? (
									<>
										<Input.TextArea
											defaultValue={reviewRemark}
											onChange={(e) => setReviewRemark(e.target.value)}
											placeholder="请输入审核意见（选填）"
											rows={4}
											style={{ marginBottom: "24px" }}
										/>

										<div
											style={{
												display: "flex",
												justifyContent: "center",
												gap: "16px",
											}}
										>
											<Button
												type="primary"
												danger
												icon={<Iconify icon="material-symbols:close" />}
												onClick={() => handleReview(-1)}
												loading={reviewLoading}
											>
												驳回
											</Button>
											<Button
												type="primary"
												icon={<Iconify icon="material-symbols:check" />}
												onClick={() => handleReview(1)}
												loading={reviewLoading}
											>
												通过
											</Button>
										</div>
									</>
								) : (
									<div
										style={{
											background: "#fafafa",
											padding: "16px",
											borderRadius: "8px",
										}}
									>
										<Space direction="vertical" size={8}>
											<div>
												<Typography.Text type="secondary">
													审核状态：
												</Typography.Text>
												<Tag
													color={
														taskSubmitStatusMap[reviewingRecord.status]?.color
													}
												>
													{taskSubmitStatusMap[reviewingRecord.status]?.text}
												</Tag>
											</div>
											<div>
												<Typography.Text type="secondary">
													审核意见：
												</Typography.Text>
												<Typography.Text>
													{reviewingRecord.remark || "-"}
												</Typography.Text>
											</div>
										</Space>
									</div>
								)}
							</div>

							<div
								style={{
									marginTop: "40px",
									display: "flex",
									justifyContent: "space-between",
									alignItems: "center",
									borderTop: "1px solid #f0f0f0",
									paddingTop: "20px",
								}}
							>
								<Button
									icon={<Iconify icon="mdi:chevron-left" />}
									disabled={!reviewingRecord?.prev}
									onClick={async () => {
										if (reviewingRecord?.prev) {
											const data = await taskService.taskSubmitInfo(
												reviewingRecord.prev.id,
											);
											setReviewingRecord(data);
										}
									}}
									style={{ maxWidth: "200px" }}
								>
									{reviewingRecord?.prev ? (
										<>
											上一条
											<Typography.Text
												type="secondary"
												style={{
													marginLeft: "8px",
													fontSize: "12px",
													overflow: "hidden",
													textOverflow: "ellipsis",
													whiteSpace: "nowrap",
												}}
											>
												#{reviewingRecord.prev.id}{" "}
												{reviewingRecord.prev.task?.title}
											</Typography.Text>
										</>
									) : (
										"上一条"
									)}
								</Button>
								<Typography.Text strong>
									{reviewingRecord.task?.title}
								</Typography.Text>
								<Button
									icon={<Iconify icon="mdi:chevron-right" />}
									disabled={!reviewingRecord?.next}
									onClick={async () => {
										if (reviewingRecord?.next) {
											const data = await taskService.taskSubmitInfo(
												reviewingRecord.next.id,
											);
											setReviewingRecord(data);
										}
									}}
									style={{ maxWidth: "200px" }}
								>
									{reviewingRecord?.next ? (
										<>
											下一条
											<Typography.Text
												type="secondary"
												style={{
													marginLeft: "8px",
													fontSize: "12px",
													overflow: "hidden",
													textOverflow: "ellipsis",
													whiteSpace: "nowrap",
												}}
											>
												#{reviewingRecord.next.id}{" "}
												{reviewingRecord.next.task?.title}
											</Typography.Text>
										</>
									) : (
										"下一条"
									)}
								</Button>
							</div>
						</div>
					)}
				</div>
			</Drawer>
			<UserDetailModal
				open={userDetailOpen}
				record={currentRecord}
				onClose={() => setUserDetailOpen(false)}
			/>
		</div>
	);
}
